package com.sunday.common.core.gson;

import com.google.gson.Gson;
import com.google.gson.ToNumberStrategy;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 解决Gson解析数据用map接收时int自动转化为double问题
 *
 * @author zsy
 * @see com.google.gson.internal.bind.ObjectTypeAdapter 原始处理类
 * @since 2022/10/10
 */
public class ObjectTypeAdapter extends TypeAdapter<Object> {

    private static final Gson gson = new Gson();

    private final ToNumberStrategy toNumberStrategy = (in) -> {
        double dbNum = in.nextDouble();
        // 改写数字的处理逻辑，将数字值分为整型与浮点型。
        if (dbNum > Long.MAX_VALUE) {
            return dbNum;
        }
        long lNum = (long) dbNum;
        // 判断数字是否为整数值
        if (dbNum == lNum) {
            if (lNum > Integer.MAX_VALUE) {
                return lNum;
            } else {
                return (int) lNum;
            }
        } else {
            return dbNum;
        }
    };

    @Override
    public Object read(JsonReader in) throws IOException {
        JsonToken token = in.peek();
        switch (token) {
            case BEGIN_ARRAY:
                List<Object> list = new ArrayList<>();
                in.beginArray();
                while (in.hasNext()) {
                    list.add(read(in));
                }
                in.endArray();
                return list;

            case BEGIN_OBJECT:
                Map<String, Object> map = new LinkedTreeMap<>();
                in.beginObject();
                while (in.hasNext()) {
                    map.put(in.nextName(), read(in));
                }
                in.endObject();
                return map;

            case STRING:
                return in.nextString();

            case NUMBER:
                return toNumberStrategy.readNumber(in);

            case BOOLEAN:
                return in.nextBoolean();

            case NULL:
                in.nextNull();
                return null;

            default:
                throw new IllegalStateException();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void write(JsonWriter out, Object value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }

        TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
        if (typeAdapter instanceof com.google.gson.internal.bind.ObjectTypeAdapter) {
            out.beginObject();
            out.endObject();
            return;
        }

        typeAdapter.write(out, value);
    }

    public static ObjectTypeAdapter getInstance() {
        return new ObjectTypeAdapter();
    }

}
